/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-02-26 16:57:25
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-03-22 16:06:56
 * @Description: file content
 */
import { Application } from "egg";
import { DataTypes, Model } from "sequelize";
import { modelCommonField } from "../../utils";

export interface sysOrgInterface extends Model {
  /** 主键id */
  id: number;
  /** 组织名称 */
  org_name: string;
  /** 组织代码 */
  org_code: string;
  /** 上级组织部门id */
  parent_org_id: number;
  /** 状态 */
  state: 0 | 1 | "1" | "0";
  /** 排序 */
  orders: number;
  /** 创建者id */
  create_user_id: number;

  /** 修改者id */
  edit_user_id: number;
}

export default (app: Application) => {
  const model = app.model.define<sysOrgInterface>(
    app.config.dbModel_prefix + "sys_org",
    {
      org_name: {
        field: "org_name",
        comment: "组织名称",
        type: DataTypes.STRING(80),
      },
      org_code: {
        field: "org_code",
        comment: "组织代码", //用户自行输入代号
        type: DataTypes.STRING(16),
      },
      parent_org_id: {
        field: "parent_org_id",
        comment: "上级组织部门id",
        type: DataTypes.INTEGER,
      },
      state: {
        field: "state",
        comment: "状态", //1启用 0禁用
        type: DataTypes.BOOLEAN,
        // validate: {
        //   isIn: {
        //     args: [["0", "1"]],
        //     msg: "state just one of 0 | 1",
        //   },
        // },
      },
      orders: {
        field: "orders",
        comment: "排序",
        type: DataTypes.INTEGER,
      },
      ...modelCommonField,
    }
  );

  (model as any).associate = () => {
    model.belongsTo(model, {
      foreignKey: "parent_org_id",
      as: "parent_org",
      constraints: false,
    });
  };

  return model;
};
